package com.azt.mq.listener;

import com.alibaba.fastjson.JSONObject;
import com.azt.api.enums.MessageEnum;
import com.azt.api.pojo.MailParam;
import com.azt.api.pojo.SmsParam;
import com.azt.mq.service.MailService;
import com.azt.mq.service.SMSService;
import org.apache.activemq.command.ActiveMQTextMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.listener.SessionAwareMessageListener;
import org.springframework.stereotype.Component;

import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.Session;


/**
 * session监听
 * 
 * @author 张栋 2016年4月25日下午2:23:24
 */
@Component
public class ConsumerSessionAwareMessageListener implements SessionAwareMessageListener<Message> {

	private static final Logger log = LoggerFactory.getLogger(ConsumerSessionAwareMessageListener.class);

	@Autowired
	private JmsTemplate activeMqJmsTemplate;

	@Autowired
	private Destination sessionAwareQueue;

	@Autowired
	private MailService mailService;

	@Autowired
	private SMSService smsService;

	public synchronized void onMessage(Message message, Session session) {
		try {
			ActiveMQTextMessage msg = (ActiveMQTextMessage) message;
			final String ms = msg.getText();
			JSONObject messageobj = JSONObject.parseObject(ms);
			log.info("messageobj" + messageobj.toJSONString());

			Integer messagetype = messageobj.getInteger("type");
			log.info("messagetype:" + messagetype);
			MessageEnum enumByIndex = MessageEnum.getEnumByIndex(messagetype);
			// 根据index拿enum
			switch (enumByIndex) {
			case EMAIL:
				MailParam mailParam = JSONObject.parseObject(ms, MailParam.class);// 转换成相应的对象
				if (mailParam == null) {
					return;
				}
				try {
					mailService.mailSend(mailParam);
					log.info(mailParam.getFrom() + "-->" + mailParam.getTo() + "   发送成功");
				} catch (Exception e) {
					log.error(mailParam.getFrom() + "-->" + mailParam.getTo() + "   发送失败");
					e.printStackTrace();
					// 发送异常，重新放回队列
					// activeMqJmsTemplate.send(sessionAwareQueue, new
					// MessageCreator() {
					// public Message createMessage(Session session) throws
					// JMSException {
					// return session.createTextMessage(ms);
					// }
					// });
				}
				break;
			case SMS:
				SmsParam smsParam = JSONObject.parseObject(ms, SmsParam.class);// 转换成相应的对象
				if (smsParam == null) {
					return;
				}
				smsService.smsSend(smsParam);
				break;

			default:
				break;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
